// 获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    actionType: '新增',
    modelid: '',
    availableTypeIndex: 0,
    model: {
      AvailableTypes: [],
      AvailableCategories: [],
    },
    allPlaces: [],
    places: [],
    categories: [],
    maxFiles: 3,
    files: [],
    showPJ: false, // 显示选择配件
    items: [],
    pageIndex: 0,
    pageSize: 15,
    value: '',
    searchPlaceValue: '',
    showPlaceAction: false,
    filter: {
      placeId: 0,
      categoryId: 0,
      name: '',
      pp: '',
      gg: '',
      location: '',
    },
    categoryActiveIndex: 0,
    categoryActiveId: null,
    showCategory: false,
    showPlace: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this;
    let planId = options.planId || '';
    _this.loadDetail(planId);
    _this.setData({
      modelid: planId
    });
  },
  loadDetail(id) {
    let _this = this;
    app.ajax({
      url: 'Maintenance/Create',
      data: {
        planId: id,
      },
      success(resp) {
        if (resp.model) {
          const _allPlaces = resp.model.AvailablePlaces || [];
          const _places = _allPlaces;
          const _categories = (resp.model.AvailableCategories.filter(m => m.PId == 0) || []).map(s => {
            var children = (resp.model.AvailableCategories.filter(m => m.PId == s.Id) || []).map(d => {
              return {
                id: d.Id,
                text: d.Text
              };
            });
            children.unshift({
              id: s.Id,
              text: s.Text,
            });
            return {
              id: s.Id,
              text: s.Text,
              children
            };
          });
          _this.setData({
            modelid: resp.model.Id,
            model: resp.model,
            places: _places,
            categories: _categories,
            allPlaces: _allPlaces,
          });
        }
      }
    });
  },
  // bindPickerChange(e) {
  //   let _this = this;
  //   const {
  //     detail: {
  //       value
  //     }
  //   } = e;
  //   const {
  //     model
  //   } = _this.data;
  //   const availableType = model.AvailableTypes[value];
  //   model.TypeId = availableType.Value;
  //   model.TypeName = availableType.Text;
  //   this.setData({
  //     availableTypeIndex: value,
  //     model
  //   });
  // },
  addImage(e) {
    let _this = this;
    wx.chooseMedia({
      mediaType: ['image'],
      sourceType: ['camera'],
      sizeType: ['compressed'],
      success: function (res) {
        let _files = _this.data.files;
        if (res.tempFiles.length + _files.length > _this.data.maxFiles) {
          wx.showToast({
            icon: 'none',
            title: `最多允许上传${_this.data.maxFiles}张图片`
          });
          return;
        }
        let startIdx = _files.length;
        for (let i = 0; i < res.tempFiles.length; i++) {
          _files.push({
            img: res.tempFiles[i].tempFilePath,
            percent: 0,
            id: 0,
            unique: startIdx + i
          });
        }
        _this.setData({
          files: _files
        }, function () {
          for (let j = 0; j < res.tempFiles.length; j++) {
            _this.uploadImg(res.tempFiles[j].tempFilePath, startIdx + j);
          }
        });
      }
    });
  },
  uploadImg(file, idx) {
    let _this = this;
    var task = wx.uploadFile({
      url: `${app.apiRoot}/Picture/AsyncUpload`,
      filePath: file,
      name: 'qqfile',
      success(resp) {
        var data = JSON.parse(resp.data) //返回的是[字符串]，需要自己转为JSON格式
        let _files = _this.data.files;
        _files[idx].id = data.pictureId;
        _this.setData({
          files: _files
        });
      },
      fail(resp) {
        console.log('fail', resp);
      }
    });

    task.onProgressUpdate((res) => {
      let _files = _this.data.files;
      _files[idx].percent = res.progress;
      _this.setData({
        files: _files
      });
    });
  },
  tapImg(e) {
    let _this = this;
    let _idx = e.currentTarget.dataset.idx
    let _files = _this.data.files;
    _files.splice(_idx, 1);
    _this.setData({
      files: _files
    });
  },
  onChange(e) {
    let _this = this;
    const {
      detail
    } = e;
    const {
      model
    } = _this.data;
    model.Comment = detail;
    this.setData({
      model
    });
  },
  loadEquipments() {
    let _this = this;
    const {
      filter: {
        name,
        pp,
        gg,
        location,
      },
      pageIndex,
      pageSize,
      model,
      items
    } = _this.data;
    let _lists = pageIndex === 0 ? [] : (items || []);
    app.ajax({
      url: 'Stock/List',
      data: {
        categoryId: model.CategoryId,
        placeId: model.PlaceId,
        name,
        pp,
        gg,
        location,
        pageIndex,
        pageSize
      },
      success(resp) {
        if (resp.result && resp.model) {
          resp.model.forEach((item) => {
            _lists.push(item);
          });
        }
        _this.setData({
          items: _lists
        });
      }
    });
  },
  scrolltolower() {
    this.setData({
      pageIndex: this.data.pageIndex + 1
    }, function () {
      this.loadEquipments();
    });
  },
  showPopupPJ() {
    const {
      model: {
        CategoryId
      }
    } = this.data;
    if (CategoryId === 0) {
      app.showNotify('请先选择设备分类');
      return;
    }
    this.loadEquipments(0);
    this.setData({
      showPJ: true
    });
  },
  onClose() {
    this.setData({
      showPJ: false,
    });
  },
  onPlaceSearch({
    detail
  }) {
    const {
      allPlaces
    } = this.data;
    const _places = (allPlaces || []).filter(m => m.Text.indexOf(detail) != -1);
    this.setData({
      searchPlaceValue: detail,
      places: _places,
    });
  },
  onPlaceFocus() {
    this.setData({
      showPlaceAction: true
    });
  },
  onPlaceCancel() {
    const {
      allPlaces
    } = this.data;
    this.setData({
      showPlaceAction: false,
      searchPlaceValue: '',
      places: allPlaces,
    });
  },
  selectPlace(e) {
    const {
      target: {
        id
      }
    } = e;
    let _this = this;
    const {
      model,
      allPlaces
    } = _this.data;
    const place = allPlaces.filter(m => m.Id == id * 1)[0];
    if (place) {
      model.PlaceId = place.Id;
      model.PlaceName = place.Text;
      _this.setData({
        showPlace: false,
        model
      });
    }
  },
  selectStock(e) {
    const {
      target: {
        id
      }
    } = e;
    let _this = this;
    const {
      model,
      items
    } = _this.data;
    const stock = items.filter(m => m.Id == id * 1)[0];
    if (stock) {
      model.EquipmentStockId = stock.Id;
      model.EquipmentId = stock.EquipmentId;
      model.PlaceId = stock.PlaceId;
      model.PlaceName = stock.PlaceName;
      model.Name = stock.Name;
      model.Manufacturer = stock.Manufacturer;
      model.Specification = stock.Specification;
      model.Location = stock.Location;
      _this.setData({
        showPJ: false,
        model
      });
    }
  },
  doSave(e) {
    let _this = this;
    const {
      model
    } = _this.data
    let _imgs = '';
    let _picDone = true;
    for (let i = 0; i < _this.data.files.length; i++) {
      if (_this.data.files[i].id <= 0) {
        _picDone = false;
        break;
      } else {
        _imgs += ',' + _this.data.files[i].id;
      }
    }
    if (!_picDone) {
      app.showNotify('请等待图片上传完成');
      return;
    }
    model.SelectedPictureIds = _imgs;
    // if (model.EquipmentId == 0) {
    //   app.showNotify('设施设备不能为空');
    //   return;
    // }
    if (!model.Comment || model.Comment.length > 50) {
      app.showNotify('情况说明不能大于50字符');
      return;
    }
    if (!model.SelectedPictureIds || model.SelectedPictureIds.length === 0) {
      app.showNotify('请上传现场图片');
      return;
    }
    app.ajax({
      url: 'Maintenance/Save',
      data: model,
      timeout: 2000,
      again: false, // 重复调用
      verifyToken: true,
      success: function (resp) {
        if (!resp.result) {
          app.showNotify(resp.msg);
        } else {
          wx.showToast({
            title: _this.data.actionType + '成功',
            complete() {
              wx.navigateBack({
                delta: 1
              });
            }
          });
          if (resp.id > 0) {
            wx.request({
              url: `${app.apiRoot}/Maintenance/SubscribeMessage`,
              method: 'POST',
              data: {
                id: resp.id,
                templateId: 'nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k'
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success(msgRes) {
                console.log(msgRes.data);
                // if (msgRes.data.success) {
                //   wx.showModal({
                //     title: '操作成功！',
                //     content: msgRes.data.msg,
                //   })
                // } else {
                //   wx.showModal({
                //     title: '操作失败！',
                //     content: msgRes.data.msg,
                //   })
                // }
              }
            })
          }
        }
      }
    });
  },
  doBack(e) {
    wx.navigateBack({
      delta: 1
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onPlaceChange({
    detail
  }) {
    const _this = this;
    const {
      filter
    } = _this.data;
    filter.placeId = detail;
    _this.setData({
      filter,
      pageIndex: 0,
      totalPages: 1
    });
    _this.loadEquipments();
  },

  // 根据筛选条件查询
  onSearch() {
    const _this = this;
    _this.selectComponent('#item').toggle();
    _this.setData({
      pageIndex: 0,
      totalPages: 1
    });
    _this.loadEquipments();
  },

  // 输入框值变化
  onFieldChange(e) {
    const _this = this;
    const {
      filter
    } = _this.data;
    const {
      detail,
      target: {
        id
      }
    } = e;
    filter[id] = detail;
    this.setData({
      filter
    });
  },

  // 输入框值变化
  onSwitchChange(e) {
    const _this = this;
    const {
      filter
    } = _this.data;
    const {
      detail,
      target: {
        id
      }
    } = e;
    filter[id] = detail;
    this.setData({
      filter
    });
  },

  // 显示设备分类选择框
  showCategory(e) {
    this.setData({
      showCategory: true
    });
  },

  // 显示巡检点选择框
  showPlace(e) {
    this.setData({
      showPlace: true,
    });
  },

  closeCategory() {
    this.setData({
      showCategory: false
    });
  },

  closePlace() {
    this.setData({
      showPlace: false
    });
  },

  onCategoryClickNav({
    detail = {}
  }) {
    console.log(detail);
    this.setData({
      categoryActiveIndex: detail.index || 0
    });
  },

  onCategoryClickItem({
    detail = {}
  }) {
    const {
      model,
      allPlaces,
    } = this.data;
    const categoryActiveId = detail.id;
    model.CategoryId = categoryActiveId;
    model.CategoryName = detail.text;

    // const _places = (allPlaces || []).filter(m => m.PId === categoryActiveId);
    this.setData({
      categoryActiveId,
      model,
      showCategory: false,
      // places: _places,
    });
  },

  confirmPlace(e) {
    const {
      detail: {
        value: {
          key,
          value
        }
      }
    } = e;
    const {
      model
    } = this.data;
    model.PlaceId = key * 1;
    model.PlaceName = value;
    this.setData({
      model,
      showPlace: false
    });
  },
})